<!--suppress NonAsciiCharacters -->
<template>
  <el-tabs :before-leave="handleSwitch" @tab-click="handleClick" v-model="activeChart" type="border-card" style="width: 1200px">
    <el-tab-pane label="任务进度" name="todoProgress">
      <v-chart v-if="activeChart === 'todoProgress'" v-loading="loading.chart" ref="todoProgress" :options="todoProgressOption"/>
    </el-tab-pane>
    <el-tab-pane label="任务耗时" name="todoConsuming">
      <v-chart v-if="activeChart === 'todoConsuming'" v-loading="loading.chart" ref="todoConsuming" :options="todoConsumingOption"/>
    </el-tab-pane>
    <el-tab-pane label="文档操作记录" name="documentData">
      <v-chart v-if="activeChart === 'documentData'" v-loading="loading.chart" ref="documentData" :options="documentDataOption"/>
      <el-select
        @change="handleDateLengthChange"
        v-if="activeChart === 'documentData'"
        v-model="currentTimeArray">
        <template slot="prefix">
          <span class="prefixSlot" title="选择操作记录展示的时间段">时间段</span>
        </template>
        <el-option v-for="time in timeArray" :value="time.value" :key="time.value" :label="time.desc"></el-option>
      </el-select>
      <el-button v-if="activeChart === 'documentData'" icon="el-icon-refresh" title="刷新图表"></el-button>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
// import {getTodos} from '@/api/todo'
import ECharts from 'vue-echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/bar'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/timeline'
import 'echarts/lib/component/toolbox'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title'
import {getTodos} from '@/api/todo'
import todoEnum from '@/utils/todoEnum'
import {loadAllLogs} from '@/api/document'

export default {
  name: 'ProjectDashboard',
  props: {
    projectId: [Number, String],
    projectName: String
  },
  components: {
    'v-chart': ECharts
  },
  data () {
    return {
      activeChart: 'todoProgress',
      loading: {
        chart: false
      },
      timeArray: [
        {
          value: 0,
          name: 'All',
          desc: '全部'
        },
        {
          value: 1,
          name: 'Week',
          desc: '一周内'
        },
        {
          value: 2,
          name: 'Month',
          desc: '一个月内'
        }
      ],
      currentTimeArray: 2,
      currentProjectTodos: [],
      logs: []
    }
  },
  mounted () {
    this.handleClick({
      name: this.activeChart
    })
  },
  methods: {
    handleClick (tab, event) {
      console.log(tab.name + '被激活了')
      switch (tab.name) {
        case 'todoProgress':
          this.loadTodoProgressOption(this.projectId)
          break
        case 'todoConsuming':
          this.loadTodoConsumingOption(this.projectId)
          break
        case 'documentData':
          this.loadDocumentDataOption(this.projectId, this.timeArray[this.currentTimeArray].name)
          break
      }
      // setTimeout(() => {
      //   this.loading.chart = false
      // }, 200)
    },
    handleSwitch (activeName, oldActiveName) {
      return true
    },
    loadTodoProgressOption (projectId) {
      getTodos(projectId, undefined, true, 0, 10000).then(res => {
        this.currentProjectTodos = res.data
      }).catch(error => {
        this.$notify.error(error)
      })
    },
    loadTodoConsumingOption (projectId) {
      getTodos(projectId, undefined, true, 0, 10000).then(res => {
        this.currentProjectTodos = res.data
      }).catch(error => {
        this.$notify.error(error)
      })
    },
    loadDocumentDataOption (projectId, dateLength) {
      loadAllLogs(projectId, dateLength).then(res => {
        this.logs = res.data
      }).catch(error => {
        this.$notify.error(error)
      })
    },
    sortMap (map, isKeyUpSort) {
      let keys = []
      for (const key of map.keys()) {
        keys.push(key)
      }

      if (isKeyUpSort) {
        keys.sort(function (key1, key2) {
          return key1 - key2
        })
      } else {
        keys.sort(function (key1, key2) {
          return key2 - key1
        })
      }

      let newMap = new Map()
      keys.forEach(key => {
        newMap.set(key, map.get(key))
      })

      return newMap
    },
    handleDateLengthChange (val) {
      this.loadDocumentDataOption(this.projectId, this.timeArray[val].name)
    }
  },
  computed: {
    todoProgressOption () {
      let todos = this.currentProjectTodos
      let topTodos = [
        {value: 0, name: '进行中'},
        {value: 0, name: '已完成'},
        {value: 0, name: '临近截止'},
        {value: 0, name: '已超时'}
      ]
      let subTodos = [
        {value: 0, name: '进行中'},
        {value: 0, name: '已完成'},
        {value: 0, name: '临近截止'},
        {value: 0, name: '已超时'}]
      let todoStatusEnum = todoEnum.TodoStatusEnum
      for (let i = 0; i < todos.length; i++) {
        let todo = todos[i]
        switch (todo.status) {
          case todoStatusEnum.APPROACHING_DEAD_LINE.name:
            if (todo.fatherId) {
              subTodos[3].value = subTodos[3].value + 1
            } else {
              topTodos[3].value = topTodos[3].value + 1
            }
            break
          case todoStatusEnum.COMPLETED.name:
            if (todo.fatherId) {
              subTodos[1].value = subTodos[1].value + 1
            } else {
              topTodos[1].value = topTodos[1].value + 1
            }
            break
          case todoStatusEnum.HANDING.name:
            if (todo.fatherId) {
              subTodos[0].value = subTodos[0].value + 1
            } else {
              topTodos[0].value = topTodos[0].value + 1
            }
            break
          case todoStatusEnum.OVERTIME.name:
            if (todo.fatherId) {
              subTodos[2].value = subTodos[2].value + 1
            } else {
              topTodos[2].value = topTodos[2].value + 1
            }
            break
        }
      }
      return {
        title: {
          text: '任务进度',
          subtext: this.projectName,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          top: 'bottom',
          data: ['进行中', '已完成', '临近截止', '已超时']
        },
        toolbox: {
          show: true,
          feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            saveAsImage: {show: true}
          }
        },
        series: [
          {
            name: '子任务进度',
            type: 'pie',
            radius: [20, 140],
            center: ['25%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 20,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: subTodos
          },
          {
            name: '顶级任务进度',
            type: 'pie',
            radius: [20, 140],
            center: ['75%', '50%'],
            roseType: 'radius',
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: true
            },
            emphasis: {
              label: {
                show: true
              }
            },
            data: topTodos
          }
        ]
      }
    },
    todoConsumingOption () {
      let todos = this.currentProjectTodos
      let dataMap = new Map()
      for (let i = 0; i < todos.length; i++) {
        let todo = todos[i]
        let cost = todo.cost
        if (dataMap[cost]) {
          if (todo.fatherId) {
            dataMap[cost]['subTodo'] += 1
          } else {
            dataMap[cost]['topTodo'] += 1
          }
        } else {
          dataMap[cost] = {
            subTodo: todo.fatherId ? 1 : 0,
            topTodo: todo.fatherId ? 0 : 1
          }
        }
      }
      console.log(dataMap)
      // dataMap = this.sortMap(dataMap)
      let xAxis = []
      let subTodo = []
      let topTodo = []
      for (let key in dataMap) {
        xAxis.push(key)
        subTodo.push(dataMap[key].subTodo)
        topTodo.push(dataMap[key].topTodo)
      }
      return {
        title: {
          text: '任务耗时分布',
          subtext: this.projectName,
          left: 'center'
        },
        legend: {
          left: 'center',
          top: 'bottom'
        },
        toolbox: {
          show: true,
          feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            saveAsImage: {show: true}
          }
        },
        xAxis: {
          type: 'category',
          name: '耗时（小时）',
          data: xAxis
        },
        yAxis: {
          type: 'value',
          name: '任务数量（个）'
        },
        series: [
          {
            name: '子任务耗时',
            type: 'line',
            label: {
              show: true
            },
            data: subTodo,
            smooth: true
          },
          {
            name: '顶级任务耗时',
            type: 'line',
            label: {
              show: true
            },
            data: topTodo,
            smooth: true
          }
        ]
      }
    },
    documentDataOption () {
      let logs = this.logs
      let logData = {
        ADD: [],
        DELETE: [],
        UPDATE: [],
        QUERY: []
      }
      for (let i = 0; i < logs.length; i++) {
        let log = logs[i]
        switch (log.type) {
          case 'ADD':
            logData.ADD.push(log)
            break
          case 'DELETE':
            logData.DELETE.push(log)
            break
          case 'UPDATE':
            logData.UPDATE.push(log)
            break
          case 'QUERY':
            logData.QUERY.push(log)
            break
        }
      }
      let addMap = new Map()
      let deleteMap = new Map()
      let updateMap = new Map()
      let queryMap = new Map()
      for (let i = 0; i < logData.ADD.length; i++) {
        let log = logData.ADD[i]
        let createTime = log['createTime'].substr(0, 10)
        if (addMap[createTime]) {
          addMap[createTime] += 1
        } else {
          addMap[createTime] = 1
        }
      }
      for (let i = 0; i < logData.DELETE.length; i++) {
        let log = logData.DELETE[i]
        let createTime = log['createTime'].substr(0, 10)
        if (deleteMap[createTime]) {
          deleteMap[createTime] += 1
        } else {
          deleteMap[createTime] = 1
        }
      }
      for (let i = 0; i < logData.UPDATE.length; i++) {
        let log = logData.UPDATE[i]
        let createTime = log['createTime'].substr(0, 10)
        if (updateMap[createTime]) {
          updateMap[createTime] += 1
        } else {
          updateMap[createTime] = 1
        }
      }
      for (let i = 0; i < logData.QUERY.length; i++) {
        let log = logData.QUERY[i]
        let createTime = log['createTime'].substr(0, 10)
        if (queryMap[createTime]) {
          queryMap[createTime] += 1
        } else {
          queryMap[createTime] = 1
        }
      }
      let addArr = []
      let delArr = []
      let updArr = []
      let queArr = []

      for (let key in addMap) {
        addArr.push([key, addMap[key]])
      }
      for (let key in deleteMap) {
        delArr.push([key, deleteMap[key]])
      }
      for (let key in updateMap) {
        updArr.push([key, updateMap[key]])
      }
      for (let key in queryMap) {
        queArr.push([key, queryMap[key]])
      }
      return {
        title: {
          text: '文档操作记录',
          subtext: this.projectName,
          left: 'center'
        },
        legend: {
          left: 'center',
          top: 'bottom',
          selected: {
            '新建': true,
            '删除': true,
            '修改': true,
            '查询': false
          },
          data: ['新建', '删除', '修改', '查询']
        },
        toolbox: {
          show: true,
          feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            saveAsImage: {show: true}
          }
        },
        xAxis: {
          type: 'time',
          name: '时间'
        },
        yAxis: {
          type: 'value',
          name: '操作次数'
        },
        series: [
          {
            name: '新建',
            type: 'line',
            label: {
              show: true
            },
            data: addArr,
            itemStyle: {
              color: '#67C23A'
            },
            smooth: false
          },
          {
            name: '删除',
            type: 'line',
            label: {
              show: true
            },
            data: delArr,
            itemStyle: {
              color: '#F56C6C'
            },
            smooth: false
          },
          {
            name: '修改',
            type: 'line',
            label: {
              show: true
            },
            data: updArr,
            itemStyle: {
              color: '#E6A23C'
            },
            smooth: false
          },
          {
            name: '查询',
            type: 'line',
            label: {
              show: true
            },
            data: queArr,
            itemStyle: {
              color: '#909399'
            },
            smooth: false
          }
        ]
      }
    }
  },
  watch: {
    projectId: {
      handler (newVal, oldVal) {
        this.projectId = newVal
        this.handleClick({
          name: this.activeChart
        })
      }
    },
    projectName: {
      handler (newVal, oldVal) {
        this.projectName = newVal
        this.$set(this.todoProgressOption.title, 'subtext', newVal)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  border: 1px solid #d9dce2;
}
.echarts {
  width: 1100px;
  height: 600px;
  margin-top: 0;
  margin-left: 0;
}
.el-select >>> .el-input--prefix .el-input__inner {
  padding-left: 110px;
}
.prefixSlot {
  height: 36px;
  width: 90px;
  display: block;
  line-height: 36px;
  border-right: 1px solid #f1f1f1;
}
</style>
